(function(){
  'use strict';
  var dictData = {
    status: {
      '0': '已使用',
      '1': '未使用'
    },
    cityId: {},
    // couponType: {
    //   '0': '夏至送券',
    //   '1': '东至送券',
    //   '2': '立秋送券',
    //   '3': '春分送券'
    // },
    plan: {},
    coupon_type: {},
    mutualType: {
      '1': '不互斥',
      '2': '全部互斥',
      '3': '指定互斥'
    }
  };
  var now = util.getTime(util.getDate(true) + ' 00:00:00');
  main(function(){

    //table
    var $tableVehicle = $('#table-vehicle');
    util.jqGrid($tableVehicle, {
      url: ajaxURL.COUPON +'/coupon/v1/planPush/getList',
      // url:"",
      // datatype: 'json',
      mtype: 'POST',
      autowidth: true,
      height: $(window).height() - 350,
      // multiselect: true,
      multiboxonly: true,
      // shrinkToFit: false,
      colModel: [
        {
          label: '用户名', name: 'userName', width: 120, formatter: function (v, o, r) {
            return '<input type="checkbox">'+'<a href="javascript:;" class="view" data-id="' + r.kid + '">' + v + '</a>';
          }
        },
        { label: '用户电话', name: 'userPhone', width: 100 },
        { label: '拉新数', name: 'newNumber', width: 120 },
        { label: '总里程(KM)', name: 'totalMileage', width: 80 },
        { label: '当月里程(KM)', name: 'monthlyMileage', width: 120 },
        { label: '状态', name: 'state', width: 120 },
        { label: '注册日期', name: 'regDate', width: 110, formatter: function (v, o, r) {
          return util.getDate(v);
        } },
        {
          label: '操作', name: 'autoNo', width: 120, formatter: function (v, o, r) {
            return '<a href="javascript:;" class="view" data-id="' + r.kid + '">' + "推送" + '</a>' ;
          }
        },
      ],
      pager: '#pager-vehicle'
    });
 // ---------------------------------弹出框 --------------------
    var planData = {};
    var cityData = {};
    var $tablePlan = $('#viewBoxDiv');
    
        util.jqGrid($tablePlan, {
          url: ajaxURL.COUPON + '/coupon/v1/plan/queryWithPage',
          // datatype: 'json',
          mtype: 'POST',
          // autowidth: true,
          height:300,
          width:1000,
          multiselect: true,
          // multiboxonly: true,
          shrinkToFit: true,
          colModel: [
            { name: 'kid', key: true, hidden: true  },
            { label: '编号', name: 'planCode',align:"center"},
            { label: '合作渠道', name: 'cooperationChannel',align:"center"},
            // { label: '邀请码', name: '', width: 100 },
            {
              label: '互斥方案', name: 'mutualType',width:100,align:"center",  formatter: function (v, o, r) {
                return dictData.mutualType[v] || '';
              }
            },
            { label: '领取上限', name: 'receiveLimt',align:"center",  width: 100},
            { label: '已领金额', name: '', width: 100,align:"center", formatter: function (v, o, r) {
              return  '100';
            }
          },
            {
              label: '有效期', name: 'valid_date',width:220,align:"center",  formatter: function (v, o, r) {
                var ret = util.getDate(r.validityStartTime) + ' 至 ' + util.getDate(r.validityEndTime);
                if (now > r.validityEndTime) {
                  ret += ' (<span class="text-danger">已过期</span>)';
                }
                return ret;
              }
            },
            { label: '操作', name: '', width: 100,align:"center", formatter: function (v, o, r) {
               return  '<a href="javascript:;" data-id='+r.kid+' class="addTextContent">添加</a>'
            }
          }
          ],
          loadComplete: function (res) {
            planData = {};
            if (res && res.data) {
              $.each(res.data, function (_, item) {
                planData[item.kid] = item;
                dictData.plan[item.kid] = item.planName
              });
            }
          },
          pager: '#pager-plan'
        }, true);



        var $tableVehicle = $('#viewBoxDiv');
    // 获取城市列表
    util.ajax(ajaxURL.ORGANIZATION + '/city/getCityList?pageNum=1&pageSize=99999', '', 'GET', util.resCallback(function (res) {
      util.selectHtml($('[name="cityId"]'), res.data, 'cityId', 'name', '请选择');
      $.each(res.data, function (_, item) {
        dictData.cityId[item.cityId] = item.name;
      });
      searchTable();
    }));

    // 获取优惠券类型
    util.ajax(ajaxURL.COUPON + '/coupon/v1/couponInfo/getAll', '', 'GET', util.resCallback(function (res) {
      util.selectHtml($('[name="coupon_type"]'), res.data, 'kid', 'couponName', '请选择');
      $.each(res.data, function (_, item) {
        dictData.coupon_type[item.kid] = item.couponName;
      });
      searchTable();
    }));

    function searchTable() {
      var data = util.formData('#form-search');
      util.searchGrid($tablePlan, data);
    }
   //点击选择弹出模态框
    $("#onclickBtn").click(function(){  
      $tablePlan.trigger("reloadGrid");
        util.layerOpen({
            title: '营销方案选择',
            content: $("#layer-plan"),
            area: ['1100px','']
          });
    });
    //用户点击选中某一项添加方案方案 
    $tableVehicle.on("click",".addTextContent",function(){
      var $this = $(this);
      var id = $this.data('id');
      
      var textShow = ""  ;
      var cheackdState = true ;
      var valueText = "";
    
         $.each(planData,function(index,value){            
              if(id == value.kid){
                valueText = value.cooperationChannel;
              if($(".textShow").length != 0){
                $.each($(".textShow"),function(index,value1){
                    var that = $(this)
                  if(id ==that.prop("id") ){
                    cheackdState = false;
                  
                      util.tip.warn('与已选方案重复...');
                 
                    return
                  }
              })
            }
                 textShow  += '<div class="textShow" id='+id+' >'+valueText+'<span class="textColor" id='+id+'>X</span></div>'
              }
      })
    if(cheackdState){
      $(".optionBox").append(textShow);
        //删除已选中的方案
      $(".optionBox").find(".textColor").each(function(){
        var that =   $(this);
        that.click(function(){
           that.parent().remove()
        if($(".textColor").length == 0){          
          $(".comfirmbox1").remove();
        }          
        })
     })
    }
    var comfirm1 = '<div class="comfirmbox1"><span class="comfirmBtn">确定</span><span class="cancelBtn">取消</span></div>';
    if($(".comfirmBtn").length == 0){
      $(".comfirmBox").append(comfirm1);
    }
    userOnclickBtn()
    cancelBtn()
  })
   //用户点击添加多项
   $(".confirmS").click(function(){
    console.log(planData)
    var textShowContent = "";
    var arr = [];
    var cheackdState = true;
    var comfirmState = false

    $.each($tableVehicle.find(":checkbox"),function(index,item){
        var that = $(this);
        var valueText  = "";
       if(that.prop("checked")){
        comfirmState = true
          // arr.push(that.parent().parent().prop("id"))
          $.each(planData,function(index,item2){
               if(that.parent().parent().prop("id") == item2.kid ){
                valueText = item2.cooperationChannel;
               }
          })
          $.each($(".textShow"),function(index,item1){
               if(item1.id == that.parent().parent().prop("id")){
                cheackdState = false;
                util.tip.warn('与已选方案重复...');             
                return
               }
          })
          textShowContent  += '<div class="textShow"  id='+that.parent().parent().prop("id")+'>'+valueText+'<span class="textColor" id='+that.parent().parent().prop("id")+'>X</span></div>'
       }
     
    })
    if(cheackdState ){
      $(".optionBox").append(textShowContent);
            //删除已选中的方案
            $(".optionBox").find(".textColor").each(function(){
              var that =   $(this);
              that.click(function(){ 
                 that.parent().remove()
                 if($(".textColor").length == 0){          
                  $(".comfirmbox1").remove();
                } 
              })
           })
    }
    var comfirm1 = '<div class="comfirmbox1"><span class="comfirmBtn">确定</span><span class="cancelBtn">取消</span></div>';
    if($(".comfirmBtn").length == 0 && comfirmState){
      $(".comfirmBox").append(comfirm1);
      userOnclickBtn()
      cancelBtn()
    }
 
   })
   //用户点击确定按钮
   function userOnclickBtn (){
    $(".comfirmBtn").click(function(){
      var contentChecked = "";
      var contentState = true;
      $.each($(".textShow"),function(index,value){
          var _id = $(this).prop("id") 
        console.log($(this).text().split("X")[0])
        contentChecked += '<div class="finalComFirm" id='+$(this).prop("id")+'>'+$(this).text().split("X")[0]+'<span class="spanContent">X</span></div>'
        $(".content-box1").find(".finalComFirm").each(function(){
           if($(this).prop("id") ==  _id){
            contentState = false
           
            return
           }
        })
      })
      if(contentState){
        $(".content-box1").append(contentChecked)
        layer.closeAll()
        $(".optionBox").html("")
        $(".comfirmBox").html("")
      }else {
        util.tip.warn('与已选方案重复...');
      }
      delContentOption()
    })
   }
   //点击模态框的取消
  function cancelBtn (){
    $(".cancelBtn").click(function(){
      layer.closeAll()
      $(".optionBox").html("")
      $(".comfirmBox").html("")
    })
  }
   //用户点击删除
   function delContentOption (){
       $(".content-box1").find(".spanContent").each(function(){
         var that = $(this);
         that.click(function(){
           $(this).parent().remove();
           
         })
       })
   }
  //点击查询
  

    //日期
    laydate.render({
      range: '至',
      elem: '#activeData',
      type: 'date',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#activeData').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    // 注册日期start
    laydate.render({
      elem: '#startDate' //指定元素
    });
    // 注册日期end
    laydate.render({
      elem: '#endDate' //指定元素
    });


  });
})(window,jQuery)
